<template>
    <Card :title="props.title" :desc="props.desc">
        <Echarts :option="option" />
    </Card>
</template>

<script setup>
import {watchEffect, reactive} from 'vue';
import _ from 'lodash';

import Card from './Card.vue';
import Echarts from './Echarts.vue';

const props = defineProps({
    config: {
        type: Object,
        default: () => {},
        required: false,
    },
    isLineAndBar: {
        type: Boolean,
        default: false,
        required: false,
    },
    title: {
        type: String,
        default: '',
        required: false,
    },
    desc: {
        type: String,
        default: '',
        required: false,
    },
});

let option = reactive({
    legend: {
        left: 'right',
    },
});

const yAxisNameTextDefaultStyle = [
    {
        align: 'right',
        padding: [0, 8, 0, 0],
    },
    {
        align: 'left',
        padding: [0, 0, 0, 8],
    },
];

const handleInit = () => {
    if (!_.isEmpty(props.config)) {
        const newOptions = _.merge({}, option, _.cloneDeep(props.config));
        newOptions.legend = _.merge(
            {},
            {
                data: _.map(newOptions.series, item => item.name),
            },
            newOptions.legend || {}
        );

        if (!_.isEmpty(newOptions.yAxis) && props.isLineAndBar) {
            newOptions.tooltip = _.merge({}, _.cloneDeep(newOptions.tooltip || {}), {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999',
                    },
                },
            });

            newOptions.yAxis = _.map(newOptions.yAxis, (item, idx) => {
                const nameTextStyle = yAxisNameTextDefaultStyle[idx];
                const mergeItem = _.merge({}, {nameTextStyle}, item);
                return mergeItem;
            });
        }
        option = reactive(newOptions);
    }
};

watchEffect(handleInit, [props]);
</script>

<style lang="css" scoped></style>
